// miniprogram/pages/main/shop/index.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    leftIndex: "",
    fee: 0,
    mealFee: 0,
    showDish: false,
    showCartPop: false,
    cartItems: [],
    freight: 0,
    showView: false,
    reduceMoney: 0,
    loading: true
  },
  cashData: {},
  /**
   * 生命周期函数--监听页面加载
   */
  showJson(url) {
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      var strs = str.split("&");
      for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
      }
    }
    return theRequest;
  },
  onLoad: function (options) {

    var visitType = options.visitType;
    if (options.scene) {
      const scene = decodeURIComponent(options.scene)
      var demo = this.showJson("?" + scene);
      if (demo.visitType) {
        visitType = demo.visitType;
      }
      if (demo.id) {
        options.id = demo.id;
      }
    } else {

    }

    if (visitType == null || visitType == undefined) {
      visitType = "visit";
    }
    app.dataRequest("/rest/visitpage/visit.htm", {
      path: "main/shop/index",
      visitType: visitType
    }, this, "visitDataXX");
    if (options.id) {
      this.shop = options.id;
      app.shop = options.id;
      var visitRequest = {};
      visitRequest.shop = options.id;
      app.dataRequest("/rest/shopvisit/create.htm", visitRequest, this, "shopvisit");

      app.postRequest("/rest/shop/viewByUser.htm", options, this.backViewData);

      var groupParam = {};
      groupParam.shopId = options.id;
      groupParam.sortField = "sortNum";
      groupParam.sortMethod = "asc";

      app.postRequest("/rest/dishgroup/list.htm", groupParam, this.backGroupData);



    } else {
      wx.reLaunch({
        url: '/pages/bootstrap/index',
      })
    }
  },
  backViewData(res) {
    if (res.code == 0) {
      this.setData({
        model: res,
        freight: res.freight,
        showView: true
      });
      app.selectShop = res;
      this.fullReductions = res.items;
      wx.setNavigationBarTitle({
        title: res.name
      })
    }
  },
  backDishData(res) {
    if (res.code == 0) {
      var list = res.list;
      if (list.length > 0) {
        list.map(item => {
          item.num = 0;
        });
        this.setData({
          dishs: list
        });
        this.dishs = list;
        var gs = this.data.groups;
        for (let index = 0; index < list.length; index++) {
          const item = list[index];
          var group = gs.find(ele => {
            return ele.id == item.dishGroup;
          })
          if (group == undefined || group == null) {
            continue;
          }
          if (group.items) {

          } else {
            group.items = [];
          }
          group.items.push(item);
        }
        this.setData({
          groups: gs
        });

      }


    }
    console.info("获取数据完成");




    var self = this;
    setTimeout(() => {
      console.info("end...")
      self.setData({
        loading: false
      });
    }, 500)
  },
  backGroupData(res) {
    console.info("获取分组数据完成");

    if (res.code == 0) {
      var list = res.list;
      this.setData({
        groups: list
      });
      if (list.length > 0) {
        this.setData({
          leftIndex: list[0].id
        });
      }
    }
    var shopParam = {};
    shopParam.shop = this.shop;
    shopParam.dishState = "onSale";
    shopParam.sortField = "dishGroup.sortNum";
    shopParam.sortMethod = "asc";

    app.postRequest("/rest/dish/stock.htm", shopParam, this.backDishData);

    console.info("获取数据");

  },
  selectCatalog(event) {
    var index = event.currentTarget.dataset.id;
    this.setData({
      leftIndex: index
    });
    this.catalog = index;
    var item = this.data.dishs.find(item => item.dishGroup == index);
    console.info(item);
    if (item) {
      //var toView = "product-" + index + "-" + item.id;
      var toView = "group-" + index;
      this.setData({
        toView: toView
      });

      this.selectCatalogTime = Date.now();
    }
    //this.initData();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  buy: function () {
    app.cartItems = this.data.cartItems;
    var totalNum = this.data.cartItems.reduce((total, item) => {
      return total + item.num;
    }, 0);
    if (totalNum <= 0) {
      app.showModal("请选择商品");
      return;
    }
    var total = app.cartItems.reduce((total, item) => {
      return total + item.subPrice;
    }, 0);
    if (this.data.model.startPrice > 0) {
      if (total < this.data.model.startPrice) {
        app.showModal("满" + this.data.model.startPrice + "元起送");
        return;
      }
    }
    app.reduceMoney = this.data.reduceMoney;
    wx.navigateTo({
      url: '/pages/main/buy/index',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  subtract: function (event) {

    var object = event.currentTarget.dataset.object;
    if (object.skuEnable) {
      this.showCart();
    } else {
      object.keyId = object.id;
      this.data.selectObj = object;
      var object = event.currentTarget.dataset.object;
      var index = event.currentTarget.dataset.index
      var group = event.currentTarget.dataset.group

      object.keyId = object.id;
      this.data.selectObj = object;
      if (object.num > 0) {
        object.num--;
        var tempIndexUpdate = "groups[" + group + "].items[" + index + "].num"
        this.setData({
          [tempIndexUpdate]: object.num
        })
      }
      this.shippingCarInfo();
    }


  },
  handleNum(object, type) {

  },
  add: function (event) {
    var object = event.currentTarget.dataset.object;

    if (object.skuEnable) {

      var selectObj = this.cashData["obj-" + object.id];
      if (selectObj == null || selectObj == undefined || !(selectObj.id)) {
        console.info("重新加载");
        var param = {};
        param.id = object.id;
        app.postRequest("/rest/dish/view.htm", param, this.backDishResponse);

      } else {
        this.setData({
          showDish: true,
          selectObj: selectObj
        });
      }

    } else {
      var object = event.currentTarget.dataset.object;
      var index = event.currentTarget.dataset.index;
      var group = event.currentTarget.dataset.group;
      if(object.limit&&object.realStock <= object.num){
        app.showModal(object.name+"库存不足");
        return;
      }
      object.num++;
      object.keyId = object.id;
      this.data.selectObj = object;


      var tempIndexUpdate = "groups[" + group + "].items[" + index + "].num"
      this.setData({
        [tempIndexUpdate]: object.num
      })



      this.shippingCarInfo();

    }
  },
  hideDishPop() {
    this.setData({
      showDish: false
    });
  },
  backDishResponse(res) {
    console.info(res);
    if (res.code == 0) {
      console.info(this.cashData);
      this.cashData["obj-" + res.id] = res;
      this.setData({
        showDish: true,
        selectObj: res
      });
    } else {
      app.showModal(res.msg);
    }
  },
  showCart() {
    this.setData({
      showCartPop: true
    });
  },
  hideCartPop() {
    this.setData({
      showCartPop: false
    });
  },
  skuClick(e) {
    const index1 = e.currentTarget.dataset.idx1;
    const index2 = e.currentTarget.dataset.idx2;
    const selectObj = this.data.selectObj;
    selectObj.specs[index1].values.forEach(ele => {
      ele.selected = false
    })
    selectObj.specs[index1].values[index2].selected = true
    this.setData({
      selectObj
    });
    this.calculateDishPrice();
  },
  calculateDishPrice() {
    const selectObj = this.data.selectObj;
    const canSubmit = this.skuCanSubmit()
    if (canSubmit) {
      var specIds = "";
      var name = "";

      if (selectObj.specs) {
        selectObj.specs.forEach(big => {
          const small = big.values.find(ele => {
            return ele.selected
          })
          specIds = specIds + big.id + ":" + small.id + ",";
          name = name + small.name + "_";
        })
      }
      console.info(specIds);

      var name = name.substring(0, name.length - 1);
      console.info(name);
      var price;
      selectObj.skus.forEach(item => {
        if (item.name == name) {
          price = item.price;
          selectObj.skuId = item.id;
          selectObj.selectName = selectObj.name + "(" + name + ")";
          selectObj.keyId = selectObj.id + "-" + item.id;
          selectObj.specTxt = name;
          selectObj.sku = true;
          selectObj.mealFee = item.mealFee;

        }
      });
      console.info(price);
      selectObj.price = price;
      this.setData({
        selectObj
      });
    }
  },
  skuCanSubmit() {
    const selectObj = this.data.selectObj;
    let canSubmit = true
    if (selectObj.specs) {
      selectObj.specs.forEach(big => {
        const small = big.values.find(ele => {
          return ele.selected
        })
        if (!small) {
          canSubmit = false
        }
      })
    }
    return canSubmit
  },
  addCart2() {
    const selectObj = this.data.selectObj;
    const canSubmit = this.skuCanSubmit()
    if (!canSubmit) {
      wx.showToast({
        title: '请选择规格',
        icon: 'none'
      })
      return
    }
    const sku = []
    if (selectObj.specs) {
      selectObj.specs.forEach(big => {
        const small = big.values.find(ele => {
          return ele.selected
        })
        sku.push({
          optionId: big.id,
          optionValueId: small.id
        })
      })
    }


    this.shippingCarInfo();
    this.hideDishPop();


    var group = this.data.groups.findIndex(item => {
      return item.id == selectObj.dishGroup;
    });
    var groupItem = this.data.groups.find(item => {
      return item.id == selectObj.dishGroup;
    });
    var index=groupItem.items.findIndex(item => {
      return item.id == selectObj.id;
    });

    var up ="groups[" + group + "].items[" + index + "].num"



    var totalNum = this.data.cartItems.reduce((total, item) => {
      if (item.dishId == selectObj.id) {
        return total + item.num;
      }
      return total;
    }, 0);

    this.setData({
      [up]: totalNum
    })

  },
  shippingCarInfo() {
    const selectObj = this.data.selectObj;
    var cartItems = this.data.cartItems;
    var cartObj = cartItems.find(item => {
      return item.keyId == selectObj.keyId;
    });
    var fee = 0;
    if (cartObj == null || cartObj == undefined) {
      cartObj = {};
      cartObj.num = selectObj.num;
      if (!(cartObj.num)) {
        cartObj.num = 1;
      }
      cartObj.keyId = selectObj.keyId;
      cartObj.dishId = selectObj.id;
      cartObj.dishGroup = selectObj.dishGroup;
      cartObj.skuId = selectObj.skuId;
      //要是sku,启用价格
      if (cartObj.skuId) {
        cartObj.price = selectObj.price;
      } else {
        cartObj.price = selectObj.salePrice;
      }
      cartObj.mealFee = selectObj.mealFee;
      cartObj.name = selectObj.name;
      cartObj.logo = selectObj.logo;
      cartObj.specTxt = selectObj.specTxt;
      cartObj.sku = selectObj.sku;
      cartItems.push(cartObj);
    } else {
      if (!(selectObj.num) && selectObj.num != 0) {
        selectObj.num = 1;
      }
      if (selectObj.sku) {
        cartObj.num = cartObj.num + selectObj.num;

      } else {
        cartObj.num = selectObj.num;
      }
    }
    cartObj.subPrice = cartObj.price * cartObj.num;
    cartObj.subMealFee = cartObj.mealFee * cartObj.num;
    this.setData({
      cartItems: cartItems
    });



    /**
     * 计算满减
     */
    var totalFull = cartItems.reduce((total, item) => {
      return total + item.subPrice;
    }, 0);
    var money = 0;
    if (this.fullReductions && this.fullReductions.length > 0) {
      for (let index = 0; index < this.fullReductions.length; index++) {
        const element = this.fullReductions[index];
        if (totalFull > element.fullMoney) {
          if (money < element.reduceMoney) {
            money = element.reduceMoney;
          }
        }
      }
    }

    var total = totalFull - money;

    if (total.toFixed) {
      total = total.toFixed(2);
    } else {
      var totalMoney = parseFloat(total + "")
      total = totalMoney.toFixed(2);
    }

    this.setData({
      fee: total,
      reduceMoney: money
    });

  },
  dishStepChange(e) {
    const selectObj = this.data.selectObj
    selectObj.num = e.detail
    this.setData({
      selectObj
    })
  },
  async cartStepChange(e) {
    var cartItems = this.data.cartItems;

    const index = e.currentTarget.dataset.idx
    const cartItem = cartItems[index];
    var selectObj = cartItem;
    if (e.detail < 1) {
      cartItems.splice(index, 1);
    } else {
      cartItem.num = e.detail;
      cartItem.subPrice = cartItem.price * cartItem.num;

    }

    var total = cartItems.reduce((total, item) => {
      return total + item.subPrice;
    }, 0);

    this.setData({
      fee: total
    });
    this.setData({
      cartItems: cartItems
    });



    
    var groupIndex = this.data.groups.findIndex(item => {
      return item.id == selectObj.dishGroup;
    });
    var groupItem = this.data.groups.find(item => {
      return item.id == selectObj.dishGroup;
    });
    var itemindex=groupItem.items.findIndex(item => {
      return item.id == selectObj.dishId;
    });
    var up ="groups[" + groupIndex + "].items[" + itemindex + "].num";




    var totalNum = this.data.cartItems.reduce((total, item) => {
      if (item.dishId == selectObj.dishId) {
        return total + item.num;
      }
      return total;
    }, 0);

    this.setData({
      [up]: totalNum
    })
  },
  onShareAppMessage: function () {

  },
  scrollTopFun(e) {
    var self = this;
    let list = this.data.dishs;
    if (list.length < 2) {
      return;
    }
    var num = 1000;
    if (this.lastTime) {
      num = Date.now() - this.lastTime;
    }
    if (num < 200) {
      console.info("访问过快");
      return;
    }
    this.lastTime = Date.now();
    if (this.selectCatalogTime) {
      var time = Date.now() - this.selectCatalogTime;
      console.info("间隔时间:" + time);
      if (time < 800) {
        return;
      }
    }

    var testTime = Date.now();

    let tabHeight = 0;

    for (let i = 0; i < list.length; i++) {
      var item = list[i];
      var toView = "#product-" + item.dishGroup + "-" + item.id;
      let view = wx.createSelectorQuery().select(toView);
      //console.info(view);
      view.fields({
        size: true
      }, res => {

        list[i].top = tabHeight;
        tabHeight = tabHeight + res.height;
        list[i].height = res.height;
        list[i].bottom = tabHeight;
      }).exec();
    }

    let scrollTop = e.detail.scrollTop;
    console.info(scrollTop);
    for (let i = 0; i < list.length; i++) {
      if (scrollTop > list[i].top && scrollTop < list[i].bottom) {
        self.setData({
          leftIndex: list[i].dishGroup
        })
        return false
      }
    }
    testTime = Date.now() - testTime;
    console.info("testTime:" + testTime)
  }

})